package com.suishoupai.xmb.controller;

import com.github.pagehelper.Page;
import com.suishoupai.xmb.entity.AjaxMessage;
import com.suishoupai.xmb.entity.Auth;
import com.suishoupai.xmb.entity.AuthTypeEnum;
import com.suishoupai.xmb.exception.XmbException;
import com.suishoupai.xmb.service.AuthService;
import com.suishoupai.xmb.utils.PageUtil;
import com.suishoupai.xmb.utils.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created by caojian on 2017/4/6.
 */
@Controller
@RequestMapping("/auth")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class AuthController {
    @Autowired
    private AuthService authService;

    /**
     * 认证列表
     *
     * @param map
     * @param model
     * @return
     */
    @GetMapping("")
    public Object index(@RequestParam Map map, Model model) {
        PageUtil.startPage(map);
        Page page = (Page) authService.getAll();
        model.addAttribute("auths", page.toPageInfo());
        return "auth-list";
    }

    /**
     * 重发激活认证
     *
     * @param auth
     * @return
     */
    @PostMapping("/re")
    @ResponseBody
    public Object re(Auth auth) {
        ValidateUtil.isEmail(auth.getEmail());
        ValidateUtil.in(auth.getType(), AuthTypeEnum.ACTIVATION.getValue());
        ValidateUtil.isNull(auth.getToken());
        try {
            authService.reActivation(auth.getEmail());
        } catch (XmbException e) {
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
        return AjaxMessage.newSuccessMsg();
    }
}
